package cn.calm.user.action;

import java.util.Collection;
import java.util.List;
import java.util.Map;

import org.apache.log4j.Logger;
import org.apache.struts2.osgi.interceptor.ServiceAware;

import cn.calm.commons.action.CurdAction;
import cn.calm.commons.entity.PageMode;
import cn.calm.commons.exception.DeskException;
import cn.calm.entity.User;
import cn.calm.user.service.IUserService;

@SuppressWarnings("rawtypes")
public class UserAction<T extends User,S extends IUserService<T>> extends
CurdAction<T,S> implements ServiceAware<IUserService> {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	public static final String SESSION_KEY_USER = "USER_SESSION_KEY";
	private static final Logger LOGGER = Logger
			.getLogger(UserAction.class);

	public String login() {
		try {
			LOGGER.debug("login start");
			T temp = service.load(t);
			if (!temp.getPassword().equals(t.getPassword())) {
				throw new DeskException("", t);
			}
			LOGGER.info("login success");
			setSession(SESSION_KEY_USER, temp);
			return "login";
		} catch (DeskException e) {
			throw new DeskException("EMUM0003");
		}  catch (Exception e) {
			LOGGER.info("",e);
			return INPUT;
		}finally {
			LOGGER.debug("login end");
		}
	}

	@Override
	public String listPage() {
		return super.listPage();
	}

	@Override
	public String getModeName() {
		return "user";
	}

	@Override
	public Map<String, List<String>> getFieldErrors() {
		return super.getFieldErrors();
	}

	@Override
	public Collection<String> getActionErrors() {
		return super.getActionErrors();
	}

	@Override
	public T getT() {
		return super.getT();
	}

	@Override
	public PageMode getPageMode() {
		return super.getPageMode();
	}

	@SuppressWarnings("unchecked")
	@Override
	public Class<T> getEntityClass() {
		return (Class<T>) User.class;
	}

	@SuppressWarnings("unchecked")
	@Override
	public void setServices(List<IUserService> arg0) {
		if (service == null) {
			if (arg0 != null && arg0.size() > 0) {
				service = (S) arg0.get(0);
			}
		}
	}
}
